/**
 * 现代化战斗引擎
 * 基于事件驱动架构的全新战斗系统，解决旧版BattleArea的复杂性问题
 */

import { 
    BattleState, 
    BattlePhase, 
    BattleStatus, 
    BattleConfig, 
    BattleResult, 
    BattleResultType,
    BattleContext,
    BattleStatistics,
    BattleParticipant
} from './types';
import { EventDrivenComponent } from '../../../infrastructure/events/EventDrivenComponent';
import { COMPONENT_EVENTS } from '../../../infrastructure/events/ComponentEvents';
import { createServiceErrorHandler } from '../../../infrastructure/error/ErrorHandlingInitializer';
import { BaseGameService } from '../../../service/base/BaseGameService';
import { HealthCheckResult } from '../../../service/base/IGameService';
import rpg_component from '../../../component/rpg_component';
import { BattlePhaseManager } from './BattlePhaseManager';
import { BattleStateManager } from './BattleStateManager';
import { CombatResolver } from './CombatResolver';
import { BattleEventEmitter } from './BattleEventEmitter';
import { BattleResultGenerator } from './BattleResultGenerator';

/**
 * 战斗引擎配置
 */
interface BattleEngineConfig {
    /** 是否启用调试模式 */
    debugMode?: boolean;
    /** 最大并发战斗数 */
    maxConcurrentBattles?: number;
    /** 默认战斗超时时间 */
    defaultTimeout?: number;
    /** 是否启用性能监控 */
    enablePerformanceMonitoring?: boolean;
}

/**
 * 现代化战斗引擎
 * 采用事件驱动架构，模块化设计，易于扩展和测试
 */
export class ModernBattleEngine extends BaseGameService {
    readonly serviceName = 'ModernBattleEngine';
    readonly dependencies = ['BattlePhaseManager', 'BattleStateManager', 'CombatResolver'];

    private phaseManager: BattlePhaseManager;
    private stateManager: BattleStateManager;
    private combatResolver: CombatResolver;
    private eventEmitter: BattleEventEmitter;
    private resultGenerator: BattleResultGenerator;
    
    // 当前活跃的战斗
    private activeBattles = new Map<string, BattleContext>();
    
    // 引擎配置
    private engineConfig: BattleEngineConfig;
    
    // 性能统计
    private performanceStats = {
        totalBattles: 0,
        avgBattleDuration: 0,
        currentConcurrentBattles: 0,
        maxConcurrentBattles: 0
    };

    constructor(container?: any, config?: BattleEngineConfig) {
        super(container);
        this.engineConfig = {
            debugMode: false,
            maxConcurrentBattles: 10,
            defaultTimeout: 60000, // 1分钟
            enablePerformanceMonitoring: true,
            ...config
        };
    }

    /**
     * 服务初始化
     */
    protected async onInit(): Promise<void> {
        this.log('info', 'Initializing Modern Battle Engine...');
        
        try {
            // 初始化各个组件
            this.phaseManager = new BattlePhaseManager();
            this.stateManager = new BattleStateManager();
            this.combatResolver = new CombatResolver();
            this.eventEmitter = new BattleEventEmitter();
            this.resultGenerator = new BattleResultGenerator();

            // 设置事件监听器
            this.setupBattleEventListeners();
            
            this.log('info', 'Modern Battle Engine initialized successfully', {
                metadata: { 
                    maxConcurrentBattles: this.engineConfig.maxConcurrentBattles,
                    debugMode: this.engineConfig.debugMode
                }
            });
            
        } catch (error) {
            this.log('error', 'Failed to initialize Modern Battle Engine', undefined, error);
            throw error;
        }
    }

    /**
     * 服务销毁
     */
    protected async onDestroy(): Promise<void> {
        this.log('info', 'Destroying Modern Battle Engine...');
        
        // 取消所有活跃战斗
        for (const [battleId, context] of this.activeBattles.entries()) {
            await this.cancelBattle(battleId, 'Engine shutdown');
        }
        
        this.activeBattles.clear();
        this.log('info', 'Modern Battle Engine destroyed');
    }

    /**
     * 健康检查
     */
    protected async onHealthCheck(): Promise<HealthCheckResult> {
        const isHealthy = this.activeBattles.size < this.engineConfig.maxConcurrentBattles!;
        
        return {
            healthy: isHealthy,
            message: isHealthy 
                ? 'Battle engine running normally' 
                : `Too many concurrent battles: ${this.activeBattles.size}/${this.engineConfig.maxConcurrentBattles}`,
            timestamp: Date.now(),
            details: {
                activeBattles: this.activeBattles.size,
                maxConcurrentBattles: this.engineConfig.maxConcurrentBattles,
                performanceStats: this.performanceStats
            }
        };
    }

    // ==================== 公共API ====================

    /**
     * 创建新战斗
     */
    async createBattle(
        homeUnits: rpg_component[], 
        awayUnits: rpg_component[],
        config?: Partial<BattleConfig>
    ): Promise<string> {
        return this.recordCall('createBattle', async () => {
            // 检查并发战斗限制
            if (this.activeBattles.size >= this.engineConfig.maxConcurrentBattles!) {
                throw new Error(`Maximum concurrent battles reached: ${this.engineConfig.maxConcurrentBattles}`);
            }

            // 生成战斗ID
            const battleId = this.generateBattleId();
            
            // 创建战斗配置
            const battleConfig: BattleConfig = {
                maxRounds: 100,
                enableSkills: true,
                enablePassiveSkills: true,
                enableAuras: true,
                enableLogging: true,
                timeout: this.engineConfig.defaultTimeout!,
                debugMode: this.engineConfig.debugMode!,
                ...config
            };

            // 创建参与者
            const homeParticipants = this.createParticipants(homeUnits, true);
            const awayParticipants = this.createParticipants(awayUnits, false);

            // 初始化战斗状态
            const initialState: BattleState = {
                battleId,
                phase: BattlePhase.PREPARING,
                status: BattleStatus.PENDING,
                currentRound: 0,
                maxRounds: battleConfig.maxRounds,
                homeParticipants,
                awayParticipants,
                startTime: Date.now(),
                config: battleConfig
            };

            // 创建战斗上下文
            const context: BattleContext = {
                state: initialState,
                rules: {
                    maxRounds: battleConfig.maxRounds,
                    timeoutRules: {
                        enabled: battleConfig.timeout > 0,
                        maxDuration: battleConfig.timeout,
                        action: 'draw'
                    },
                    fleeRules: {
                        enabled: false,
                        successRate: 0.5
                    },
                    reviveRules: {
                        enabled: false,
                        maxRevives: 0,
                        reviveHealthPercent: 0.5
                    }
                },
                eventHistory: [],
                logs: [],
                temporaryData: new Map()
            };

            // 注册战斗
            this.activeBattles.set(battleId, context);
            this.performanceStats.currentConcurrentBattles = this.activeBattles.size;
            this.performanceStats.maxConcurrentBattles = Math.max(
                this.performanceStats.maxConcurrentBattles,
                this.activeBattles.size
            );

            this.log('info', `Battle created: ${battleId}`, {
                metadata: {
                    homeUnits: homeParticipants.length,
                    awayUnits: awayParticipants.length,
                    config: battleConfig
                }
            });

            // 发射战斗创建事件
            await this.eventEmitter.emitBattleEvent('battle.created', context, {
                battleId,
                participants: [...homeParticipants, ...awayParticipants]
            });

            return battleId;
        });
    }

    /**
     * 开始战斗
     */
    async startBattle(battleId: string): Promise<BattleResult> {
        return this.recordCall('startBattle', async () => {
            const context = this.activeBattles.get(battleId);
            if (!context) {
                throw new Error(`Battle not found: ${battleId}`);
            }

            if (context.state.status !== BattleStatus.PENDING) {
                throw new Error(`Battle ${battleId} is not in pending status: ${context.state.status}`);
            }

            this.log('info', `Starting battle: ${battleId}`);

            try {
                // 更新状态为活跃
                context.state.status = BattleStatus.ACTIVE;
                context.state.phase = BattlePhase.INITIALIZING;

                // 发射战斗开始事件
                await this.eventEmitter.emitBattleEvent('battle.started', context, {
                    battleId,
                    startTime: context.state.startTime
                });

                // 执行战斗流程
                const result = await this.executeBattleFlow(context);

                // 清理战斗
                this.activeBattles.delete(battleId);
                this.performanceStats.currentConcurrentBattles = this.activeBattles.size;
                this.performanceStats.totalBattles++;

                // 更新性能统计
                if (this.engineConfig.enablePerformanceMonitoring) {
                    this.updatePerformanceStats(result);
                }

                this.log('info', `Battle completed: ${battleId}`, {
                    metadata: {
                        resultType: result.resultType,
                        duration: result.statistics.duration,
                        rounds: result.statistics.totalRounds
                    }
                });

                return result;

            } catch (error) {
                // 战斗失败处理
                await this.handleBattleError(context, error as Error);
                throw error;
            }
        });
    }

    /**
     * 取消战斗
     */
    async cancelBattle(battleId: string, reason: string): Promise<void> {
        return this.recordCall('cancelBattle', async () => {
            const context = this.activeBattles.get(battleId);
            if (!context) {
                return; // 战斗不存在，直接返回
            }

            this.log('info', `Cancelling battle: ${battleId}`, { metadata: { reason } });

            // 更新状态
            context.state.status = BattleStatus.CANCELLED;
            context.state.endTime = Date.now();

            // 发射取消事件
            await this.eventEmitter.emitBattleEvent('battle.cancelled', context, {
                battleId,
                reason,
                cancelledAt: Date.now()
            });

            // 清理
            this.activeBattles.delete(battleId);
            this.performanceStats.currentConcurrentBattles = this.activeBattles.size;
        });
    }

    /**
     * 获取战斗状态
     */
    getBattleState(battleId: string): BattleState | null {
        const context = this.activeBattles.get(battleId);
        return context ? { ...context.state } : null;
    }

    /**
     * 获取所有活跃战斗
     */
    getActiveBattles(): string[] {
        return Array.from(this.activeBattles.keys());
    }

    /**
     * 获取性能统计
     */
    getPerformanceStats() {
        return { ...this.performanceStats };
    }

    // ==================== 私有方法 ====================

    /**
     * 设置战斗事件监听器
     */
    private setupBattleEventListeners(): void {
        // 监听战斗相关事件，可以在这里添加额外的处理逻辑
        this.eventEmitter.on('battle.phase.changed', async (data) => {
            this.log('debug', `Battle phase changed: ${data.battleId}`, {
                metadata: { 
                    fromPhase: data.fromPhase, 
                    toPhase: data.toPhase 
                }
            });
        });

        this.eventEmitter.on('battle.error', async (data) => {
            this.log('error', `Battle error: ${data.battleId}`, {
                metadata: { error: data.error }
            });
        });
    }

    /**
     * 执行战斗流程
     */
    private async executeBattleFlow(context: BattleContext): Promise<BattleResult> {
        let currentContext = context;

        try {
            // 执行战斗阶段流程
            while (currentContext.state.phase !== BattlePhase.COMPLETED) {
                currentContext = await this.phaseManager.processPhase(currentContext);
                
                // 检查是否需要中断
                if (this.shouldInterruptBattle(currentContext)) {
                    break;
                }
            }

            // 生成战斗结果
            const result = await this.resultGenerator.generateResult(currentContext);
            
            // 发射战斗结束事件
            await this.eventEmitter.emitBattleEvent('battle.completed', currentContext, {
                result
            });

            return result;

        } catch (error) {
            this.log('error', `Battle flow execution failed: ${context.state.battleId}`, undefined, error);
            throw error;
        }
    }

    /**
     * 检查是否应该中断战斗
     */
    private shouldInterruptBattle(context: BattleContext): boolean {
        // 超时检查
        if (context.rules.timeoutRules.enabled) {
            const duration = Date.now() - context.state.startTime;
            if (duration > context.rules.timeoutRules.maxDuration) {
                context.state.status = BattleStatus.COMPLETED;
                context.state.phase = BattlePhase.COMPLETED;
                return true;
            }
        }

        // 最大回合数检查
        if (context.state.currentRound >= context.state.maxRounds) {
            context.state.status = BattleStatus.COMPLETED;
            context.state.phase = BattlePhase.COMPLETED;
            return true;
        }

        // 状态检查
        if (context.state.status === BattleStatus.CANCELLED || 
            context.state.status === BattleStatus.ERROR) {
            return true;
        }

        return false;
    }

    /**
     * 处理战斗错误
     */
    private async handleBattleError(context: BattleContext, error: Error): Promise<void> {
        context.state.status = BattleStatus.ERROR;
        context.state.endTime = Date.now();

        await this.eventEmitter.emitBattleEvent('battle.error', context, {
            error: error.message,
            stack: error.stack,
            timestamp: Date.now()
        });

        // 清理
        this.activeBattles.delete(context.state.battleId);
        this.performanceStats.currentConcurrentBattles = this.activeBattles.size;

        this.log('error', `Battle error handled: ${context.state.battleId}`, undefined, error);
    }

    /**
     * 创建参与者
     */
    private createParticipants(units: rpg_component[], isHome: boolean): BattleParticipant[] {
        return units.map(unit => ({
            id: unit.id,
            name: unit.getComponent ? unit.getComponent('base')?.nickName || unit.id : unit.id,
            component: unit,
            isHome,
            isAlive: !unit.isDie(),
            type: unit.masterId ? 'pet' : 'player',
            masterId: unit.masterId
        }));
    }

    /**
     * 生成战斗ID
     */
    private generateBattleId(): string {
        const timestamp = Date.now().toString(36);
        const random = Math.random().toString(36).substr(2, 9);
        return `battle_${timestamp}_${random}`;
    }

    /**
     * 更新性能统计
     */
    private updatePerformanceStats(result: BattleResult): void {
        const duration = result.statistics.duration;
        const totalBattles = this.performanceStats.totalBattles;
        
        this.performanceStats.avgBattleDuration = 
            (this.performanceStats.avgBattleDuration * (totalBattles - 1) + duration) / totalBattles;
    }
}

/**
 * 便捷的战斗引擎创建函数
 */
export function createModernBattleEngine(config?: BattleEngineConfig): ModernBattleEngine {
    return new ModernBattleEngine(undefined, config);
}
